package com.mobilepay.moneypig.model.activity.search;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.model.activity.mine.AddCardActivity;
import com.mobilepay.moneypig.model.activity.search.util.ChineseSpelling;
import com.mobilepay.moneypig.model.activity.search.util.ClearEditText;
import com.mobilepay.moneypig.model.activity.search.util.Cn2Spell;
import com.mobilepay.moneypig.model.activity.search.util.ContactRecyclerAdapter;
import com.mobilepay.moneypig.model.activity.search.util.OnRecyclerViewListener;
import com.mobilepay.moneypig.model.activity.search.util.SideBar;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.address.AddressData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xlm on 2017/8/18 0018
 */

public class BankActivity extends BaseActivity {

    //数据源
    private List<AddressData.DataBean> exampleList;
    private List<AddressData.DataBean> tempExampleList;//实际操作数据
    //搜索框
    private ClearEditText mClearEditText;
    private TextView tvNoResult;//如果结果为空，则显示
    //侧边栏
    private SideBar sideBar;
    private TextView anno;
    //列表
    private RecyclerView recyclerView;
    private ContactRecyclerAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    private RelativeLayout mBankBack;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_bank);
    }

    @Override
    protected void initViews() {
        tvNoResult = (TextView) findViewById(R.id.noResult);
        mBankBack = (RelativeLayout) findViewById(R.id.bank_back);
        //此处老是提示空指针错误，有人知道为什么吗
        //是在一次AS升级之后出现的，知道的话发我邮箱指导一下，谢谢
        tvNoResult.setVisibility(View.GONE);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        initData();
        initRecyclerView();
        initSideBar();
        initSearchEdtit();
        getBankName();
    }

    @Override
    protected void onSetListener() {
        mBankBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 搜索栏
     */
    private void initSearchEdtit() {
        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    /**
     * 获取每个字符或者直接用 toCharArray 方法
     * 通过检索输入的字符，是不是顺序匹配pinyin项实现筛选
     *
     * @param s 搜索条件
     */
    private void filterData(String s) {
        tempExampleList.clear();
        if (TextUtils.isEmpty(s)) {
            tempExampleList.addAll(exampleList);
        } else {
            //判断首字母是否为字母
            Pattern p = Pattern.compile("[a-zA-Z]");
            Matcher m = p.matcher(s.substring(0, 1));
            if (m.matches()) {//字母
                for (AddressData.DataBean contact : exampleList) {
                    //拼音
                    if (s.length() == 1) {
                        //按首字母搜索
                        String[] str = contact.getPinyin().split(" ");
                        for (String aStr : str) {
                            if (aStr.startsWith(s)) {
                                tempExampleList.add(contact);
                            }
                        }
                    } else {
                        // 全拼匹配
                        if (s.length() < 6) {
                            String firstLetters = Cn2Spell.getPinYinHeadChar(contact.getName());
                            // 不区分大小写
                            Pattern firstLetterMatcher = Pattern.compile(s, Pattern.CASE_INSENSITIVE);
                            boolean b = firstLetterMatcher.matcher(firstLetters).find();
                            if (b) {
                                tempExampleList.add(contact);
                            }
                        } else {
                            Pattern pattern2 = Pattern.compile(s, Pattern.CASE_INSENSITIVE);
                            Matcher matcher2 = pattern2.matcher(Cn2Spell.getSelling(s));
                            boolean c = matcher2.find();
                            if (c) {
                                tempExampleList.add(contact);
                            }
                        }
                    }
                }
            } else {
                //输入汉字
                ChineseSpelling finder = ChineseSpelling.getInstance();
                String result;
                for (AddressData.DataBean contact : exampleList) {
                    // 先将输入的字符串转换为拼音
                    finder.setResource(s);
                    result = finder.getSpelling();
                    if (contains(contact, result)) {
                        tempExampleList.add(contact);
                    } else if (contact.getName().contains(s)) {
                        tempExampleList.add(contact);
                    }
                }
            }
            //放置没有搜索结果的文本
            if (tempExampleList.size() == 0) {
                tvNoResult.setVisibility(View.VISIBLE);
            } else {
                tvNoResult.setVisibility(View.GONE);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 根据拼音搜索
     * 搜索条件是否大于6个字符
     *
     * @return
     */
    public static boolean contains(AddressData.DataBean contact, String search) {
        if (TextUtils.isEmpty(contact.getName())) {
            return false;
        }
        boolean flag = false;
        // 简拼匹配,如果输入在字符串长度大于6就不按首字母匹配了
        if (search.length() < 6) {
            String firstLetters = contact.getFirstLetter();
            // 不区分大小写
            Pattern firstLetterMatcher = Pattern.compile(search, Pattern.CASE_INSENSITIVE);
            flag = firstLetterMatcher.matcher(firstLetters).find();
        }
        if (!flag) { // 如果简拼已经找到了，就不使用全拼了
            // 全拼匹配
            ChineseSpelling finder = ChineseSpelling.getInstance();
            finder.setResource(contact.getName());
            // 不区分大小写
            Pattern pattern2 = Pattern.compile(search, Pattern.CASE_INSENSITIVE);
            Matcher matcher2 = pattern2.matcher(finder.getSpelling());
            flag = matcher2.find();
        }
        return flag;
    }

    /**
     * 排序
     */
    private void sortList() {
        for (AddressData.DataBean dataBean : exampleList) {
            String pinyin = Cn2Spell.getPinYin(dataBean.getName()); // 根据姓名获取拼音
            String firstLetter = pinyin.substring(0, 1).toUpperCase(); // 获取拼音首字母并转成大写
            if (!firstLetter.matches("[A-Z]")) { // 如果不在A-Z中则默认为“#”
                firstLetter = "#";
            }
            String headers = Cn2Spell.getPinYinHeadChar(dataBean.getName());
            dataBean.setPinyin(pinyin);
            dataBean.setFirstLetter(firstLetter);
            dataBean.setAllLetter(headers);
        }
        Collections.sort(exampleList);
    }

    /**
     * 侧边音序索引
     */
    private void initSideBar() {
        sideBar = (SideBar) findViewById(R.id.sideBar);
        anno = (TextView) findViewById(R.id.anno);
        anno.setVisibility(View.GONE);
        sideBar.setTextView(anno);
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    ((LinearLayoutManager) mLayoutManager).scrollToPositionWithOffset(position, 0);
                }
            }
        });
    }

    /**
     * 列表
     */
    private void initRecyclerView() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        mAdapter = new ContactRecyclerAdapter(tempExampleList);
        mAdapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent();
                intent.putExtra("name", tempExampleList.get(position).getName());
                intent.setClass(BankActivity.this, AddCardActivity.class);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

        mLayoutManager = new LinearLayoutManager(BankActivity.this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(mAdapter));
        recyclerView.setAdapter(mAdapter);
    }

    private void initData() {
        tempExampleList = new ArrayList<>();
        exampleList = new ArrayList<>();
    }

    private void getBankName() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("model", "bank1");
        param.add("pid", "0");
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executeProviceGet(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString("bank");
                    if (!CommonUtil.isEmpty(jsonString)) {
                        setBankData(jsonString);
                    }
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    setBankData(string);
                    ACache.get(App.getApp()).put("bank", string);
                }
            }
        });
    }

    private void setBankData(String string) {
        try {
            JSONObject jsonObject = new JSONObject(string);
            if (jsonObject.get("data") != null) {
                AddressData data = GsonUtil.GsonToBean(string, AddressData.class);
                List<AddressData.DataBean> dataBeanList = data.getData();
                if (dataBeanList.size() != 0) {
                    exampleList.addAll(dataBeanList);
                    sortList();
                    tempExampleList.addAll(exampleList);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
